package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttrTemplate;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.goods.BAIZEAPI;
import com.ruoyi.system.outto.goods.RENYIAPI;
import com.ruoyi.system.token.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.ContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class BAIZEAPIImpl implements BAIZEAPI {
    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;


    //获取token
    public static String getToken(SalePartner salePartner) {
        String url = "http://api.baizewy.com/webApi/api_token";
        Map<String, String> params = new TreeMap<>();
        long timestamp = System.currentTimeMillis() / 1000;
        String cover = timestamp + salePartner.getTwoOther() + salePartner.getSaleKey();
        String sign = DigestUtils.md5Hex(cover);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", sign);
        Map<String, String> action1 = new TreeMap<>();
        action1.put("appId", salePartner.getTwoOther());
        String response = HttpUtil.doGet(url, action1, params);
        if(!response.contains("token")){
            throw new GlobalException("获取token失败!!!"+salePartner.getOther()+salePartner.getTwoOther() + salePartner.getSaleKey());
        }
        String data = JSONObject.parseObject(response).getString("data");
        String token = JSONObject.parseObject(data).getString("token");
        return token;
    }

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
//        this.appid = salePartner.getTwoOther();
//        this.appSecret = salePartner.getSaleKey();
//        this.baseUrl = salePartner.getOther();
        String token = getToken(salePartner);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
        Map<String, Object> header = new TreeMap<>();
        header.put("token", token);
        Long time = System.currentTimeMillis();
        header.put("timestamp", String.valueOf(time));
        String cover = MapUntils.getCover(params) + salePartner.getSaleKey() + token + String.valueOf(time);
        log.info(cover);
        String sign = MD5Util.encode(cover);
        header.put("sign", sign);
        log.info("白泽新增请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtil.postRequest("http://api.baizewy.com/webApi/goods/publish", params, ContentType.APPLICATION_JSON, null, header);


        log.info("白泽新增返回参数={}", MapUntils.unicodeToString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        if(resultJson.toJSONString().contains("result")){
            String results = resultJson.getString("result");
            JSONObject resultJsons = JSONObject.parseObject(results);
            if (!"200".equals(resultJsons.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                String data = resultJson.getString("data");
                JSONObject resultJsonss = JSONObject.parseObject(data);
                result.put("outId", resultJsonss.getString("pid"));
                on(token, resultJsonss.getString("pid"),salePartner);
            }
        }else {
            result.put("code", 500);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
//        this.appid = salePartner.getTwoOther();
//        this.appSecret = salePartner.getSaleKey();
//        this.baseUrl = salePartner.getOther();
//        String token = getToken();
        return addGame(goodsInfoAndAttrValueDto,salePartner);
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> paramss = new TreeMap<>();
        //属性匹配
        Property(goodsInfoAndAttrValueDto, paramss, salePartner);
        if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")) {
                paramss.put("groupId", 41545);
                paramss.put("serverId", 41718);
            } else {
                paramss.put("groupId", 41546);
                paramss.put("serverId", 41719);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("暗区突围")) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")) {
                paramss.put("groupId", 52286);
                paramss.put("serverId", 53327);
            } else {
                paramss.put("groupId", 52289);
                paramss.put("serverId", 53326);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")) {
                paramss.put("groupId", 52689);
                paramss.put("serverId", 53329);
            } else {
                paramss.put("groupId", 52686);
                paramss.put("serverId", 53328);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")) {
                paramss.put("groupId", 53320);
                paramss.put("serverId", 53330);
            } else {
                paramss.put("groupId", 53323);
                paramss.put("serverId", 53331);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")) {
            if(goodsInfoAndAttrValueDto.getServerName().contains("手机")){
                paramss.put("f1", 55649);
            }else if(goodsInfoAndAttrValueDto.getServerName().contains("邮箱")){
                paramss.put("f1", 55650);
            }else {
                paramss.put("f1", 55648);
            }
            if(goodsInfoAndAttrValueDto.getGroupName().contains("网易")){
                paramss.put("serverId", 55615);
            }else if(goodsInfoAndAttrValueDto.getGroupName().contains("Steam")){
                paramss.put("serverId", 55617);
            }else {
                paramss.put("serverId", 55619);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")) {
            paramss.put("systemId", 79711);
            paramss.put("carrierId", 79701);
            if(goodsInfoAndAttrValueDto.getServerName().contains("手机")) {
                paramss.put("groupId", 79714);
                paramss.put("serverId", 79722);
            }else {
                paramss.put("groupId", 79715);
                paramss.put("serverId", 79723);
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("无畏契约")) {
            paramss.put("groupId", 54660);
            paramss.put("serverId", 54662);
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")) {
                paramss.put("groupId", 94180);
                paramss.put("serverId", 94183);
            } else {
                paramss.put("groupId", 94181);
                paramss.put("serverId", 94182);
            }
        }



        paramss.put("importantRemark", StringUtils.isEmpty(goodsInfoAndAttrValueDto.getImportantRemark())  ? "无" : goodsInfoAndAttrValueDto.getImportantRemark());
        paramss.put("problemDes", StringUtils.isEmpty(goodsInfoAndAttrValueDto.getProblemDes()) ? "无" : goodsInfoAndAttrValueDto.getProblemDes());
        paramss.put("accountNumber", StringUtils.isEmpty(goodsInfoAndAttrValueDto.getAccountNumber()) ? 123456 : goodsInfoAndAttrValueDto.getAccountNumber().trim());
        paramss.put("accountPassword", 123456);
        paramss.put("thirdId", goodsInfoAndAttrValueDto.getId());
        paramss.put("title", goodsInfoAndAttrValueDto.getTitle().length()>199?goodsInfoAndAttrValueDto.getTitle().substring(0,190):goodsInfoAndAttrValueDto.getTitle());
        paramss.put("titleImg", goodsInfoAndAttrValueDto.getTitleImg());
        paramss.put("price", goodsInfoAndAttrValueDto.getPrice());
        paramss.put("des", goodsInfoAndAttrValueDto.getDes());

        List<Map<String, Object>> urlArr = goodsInfoAndAttrValueDto.getUrlArr();
        StringBuffer imgs = new StringBuffer();
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())){
            imgs.append(goodsInfoAndAttrValueDto.getTitleImg()+",");
        }
        for(Map<String, Object> maps : urlArr){
            String ss = String.valueOf(maps.get("url"));
            String imgStr = ss + ",";
            imgs.append(imgStr);
        }
        String imgUrls = imgs.toString().substring(0, imgs.length() - 1);
        paramss.put("imgUrls", imgUrls);
        return paramss;
    }
    private Map Property(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, SalePartner salePartner) {

        String substring = salePartner.getSaleName();
        if (substring.contains("_")) {
            substring = substring.substring(salePartner.getSaleName().indexOf("_")+1);
        }
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());

        params.put("gameId", interAttr.getInterGameId());
        params.put("gameType", goodsInfoAndAttrValueDto.getGameType());


        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, params, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, params, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, params, interAttr.getInputAttr());
        return params;
    }
    /**
     * 开始匹配区服属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param params
     * @param server
     */
    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {

        Long systemId = null;
        Long carrierId = null;
        Long groupId = null;
        Long serverId = null;
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
        if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            for (JSONObject json : oneServer) {
                if(Objects.equals(json.getLong("YdServeId"), goodsInfoAndAttrValueDto.getSystemId())){
                    systemId = json.getLong("InterServeId");
                }
                List<JSONObject> array = JSONObject.parseArray(json.getString("interServerRes"), JSONObject.class);
                for(JSONObject jsonObject1 : array){
                    if (Objects.equals(jsonObject1.getLong("YdServeId"), goodsInfoAndAttrValueDto.getCarrierId())) {
                        carrierId = jsonObject1.getLong("InterServeId");
                    }
                    List<JSONObject> array1 = JSONObject.parseArray(jsonObject1.getString("interServerRes"), JSONObject.class);
                    for(JSONObject jsonObject2 : array1){
                        if (Objects.equals(jsonObject2.getLong("YdServeId"), goodsInfoAndAttrValueDto.getGroupId())) {
                            groupId = jsonObject2.getLong("InterServeId");
                        }
                        List<JSONObject> array2 = JSONObject.parseArray(jsonObject2.getString("interServerRes"), JSONObject.class);
                        for(JSONObject jsonObject3 : array2){
                            if (Objects.equals(jsonObject3.getLong("YdServeId"), goodsInfoAndAttrValueDto.getServerId())) {
                                serverId = jsonObject3.getLong("InterServeId");
                            }
                        }
                    }
                }
            }
            params.put("systemId", systemId);
            params.put("carrierId", carrierId);
            params.put("groupId", groupId);
            params.put("serverId", serverId);
        } else {
            for (JSONObject json : oneServer) {
                if(Objects.equals(json.getLong("YdServeId"), goodsInfoAndAttrValueDto.getGroupId())){
                    groupId = json.getLong("InterServeId");
                }
                List<JSONObject> array = JSONObject.parseArray(json.getString("interServerRes"), JSONObject.class);
                for(JSONObject jsonObject1 : array){
                    if (Objects.equals(jsonObject1.getLong("YdServeId"), goodsInfoAndAttrValueDto.getServerId())) {
                        serverId = jsonObject1.getLong("InterServeId");
                    }
                }
            }
            params.put("groupId", groupId);
            params.put("serverId", serverId);
        }
    }

    /**
     * 开始匹配单选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param params
     * @param radioAttr
     */
    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String radioAttr) {

        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                HashMap<String, Object> mateMap = new HashMap<>();
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            String InterConfigId = object.getString("InterConfigId");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                if(StringUtils.isNotEmpty(oneValue)) {
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                    Boolean required = object.getBoolean("required");
                                    String interConfigName = object.getString("InterConfigName");
                                    String defaultValue = object.getString("defaultValue");
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && required) {
                                        if (StringUtils.isNotEmpty(defaultValue)) {
                                            params.put(InterConfigId, defaultValue);
                                        }
                                    }
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && required && StringUtils.isEmpty(defaultValue)) {
                                        throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
                                    }
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        String interConfigId2 = jsonObject2.getString("InterConfigId");
                                        params.put(InterConfigId, interConfigId2);

                                    }
                                }else {
                                    params.put(InterConfigId, jsonObjects2.get(0).getString("id"));
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            HashMap<String, Object> mateMap = new HashMap<>();
            String id = object.getString("id");
            String interRadioReqss = object.getString("interRadioReqs");
            List<JSONObject> jsonObjectss = JSONObject.parseArray(interRadioReqss, JSONObject.class);
            for(JSONObject jsonObject1 : jsonObjectss){
                if(StringUtils.isNotEmpty(jsonObject1.getString("defaultValue"))){
                    params.put(id, jsonObject1.getString("defaultValue"));
                    break;
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    /**
     * 开始匹配多选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param params
     * @param checkAttr
     */
    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String checkAttr) {
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            HashMap<String, Object> mateMap = new HashMap<>();
            String InterConfigId = object.getString("InterConfigId");
            List<String> list = new ArrayList<>();
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                //一级属性
                                String ydConfigId = object.getString("YdConfigId");
                                String InterConfigName = object.getString("InterConfigName");

                                Boolean required = object.getBoolean("required");
                                if (StringUtils.isNotEmpty(ydConfigId)) {
                                    ydConfigId = ydConfigId.replace(" ","");
                                    String[] split = ydConfigId.split(",");
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */

                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                for (String s : split1) {
                                                    if (Objects.equals(s, ydConfigId1)) {
                                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                        list.add(InterConfigId2);
                                                    }
                                                }
                                            }
                                            if (StringUtils.isEmpty(oneValue) && required){
                                                throw new GlobalException("1属性" + InterConfigName + "必传，但是暂未匹配");
                                            }
                                        }
                                        if (org.springframework.util.CollectionUtils.isEmpty(list) && required) {
                                            throw new GlobalException("2属性" + InterConfigName + "必传，但是暂未匹配");
                                        }

                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(list)) {
                mateMap.put("id", InterConfigId);
                mateMap.put("val", list);
                params.put(InterConfigId, StringUtils.join(list, ","));
            }
        }
        //========================多选属性匹配完成=====================//
    }

    /**
     * 开始匹配输入框属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param params
     * @param inputAttr
     */
    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String inputAttr) {
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            String oneValue = null;
                            try {
                                oneValue = (String) declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            Boolean required = object.getBoolean("required");
                            if (required && StringUtils.isEmpty(oneValue)) {
                                throw new GlobalException(aavNameInter + "必传，但是该商品没有该值");
                            }
                            if (StringUtils.isNotEmpty(oneValue)) {
                                params.put(interId, oneValue);
                            }
                        }
                    }
                }

            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            HashMap<String, Object> mateMap = new HashMap<>();
            String id = object.getString("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                params.put(id, 0);
            }
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String token = getToken(salePartner);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> header = new TreeMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("pid", artRec.getOutid());
        header.put("token", token);
        Long time = System.currentTimeMillis() / 1000;
        header.put("timestamp", String.valueOf(time));
        String cover = MapUntils.getCover(params) + salePartner.getSaleKey() + token + String.valueOf(time);
//        String sign = DigestUtils.md5Hex(cover);
        String sign = MD5Util.encode(cover);
        header.put("sign", sign);
        log.info("白泽新增请求参数={}", params);
        String response = HttpUtil.postRequest("http://api.baizewy.com/webApi/goods/off", params, ContentType.APPLICATION_JSON, null, header);
        params.put("sign",sign);
        log.info("白泽删除接口返回参数={}", response);
        JSONObject resultJson = null;
        try {
            resultJson = JSONObject.parseObject(response);
        }catch (Exception e){
            throw new GlobalException("错误信息"+salePartner.getSaleName());
        }
        if(resultJson.toJSONString().contains("result")){
            String results = resultJson.getString("result");
            resultJson = JSONObject.parseObject(results);
        }
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        artRecMapper.updateArtRec(artRec);
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson);
        return AjaxResult.success(result);
    }

    public static String getCover(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (key.equals("urlArr")) {
                Object a = params.get(key);
//                log.info(a.toString());
//                log.info(a.toString().replaceAll(" ",""));
                value = a.toString().replace("}, ", "},");
            }

            resut.append(key + "=" + value + "&");
        }

        return resut.toString();
    }

    public static void main(String[] args) {
//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey("ff8080818f092133018f0e1522b50010");
//        salePartner.setOther("http://back.yoyo868.com/");
//        salePartner.setTwoOther("yudoudaishou");
//        String gameList = getGameAttrTemp(salePartner,27l);
//        System.out.println(gameList);
    }

    public static String getCover1(Map<String, String> params) {
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            resut.append(key + "=" + params.get(key) + "&");
        }

        return resut.toString();
    }

    //上架
    public static String on(String token, String goodsId, SalePartner salePartner) {
        String url = "http://api.baizewy.com/webApi/goods/on";
        Long time = System.currentTimeMillis();
        Map<String, Object> header = new TreeMap<>();
        header.put("token", token);
        header.put("timestamp", time);
        Map<String, Object> paramss = new TreeMap<>();
        paramss.put("pid", goodsId);
        String cover = MapUntils.getCover(paramss) + salePartner.getSaleKey() + token + String.valueOf(time);
        String sign = DigestUtils.md5Hex(cover);
        header.put("sign", sign);
        String response = HttpUtil.postRequest(url, paramss, ContentType.APPLICATION_JSON, null, header);
        return response;
    }

}
